/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.sigawe.gateway.xml;

import java.io.IOException;
import java.io.StringReader;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import net.sigawe.gateway.Properties.Loader;
import net.sigawe.gateway.dao.impl.InboxDAO;
import net.sigawe.gateway.dao.impl.OutboxDAO;
import net.sigawe.gateway.db.DBConnection;
import net.sigawe.gateway.io.message;
import net.sigawe.gateway.model.Inbox;
import net.sigawe.gateway.model.Outbox;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import net.sigawe.gateway.dao.impl.AccountDAO;
import net.sigawe.gateway.model.Account;

/**
 *
 * @author ServerGawe
 */
public class XMLFactory {

    private message message = new message();
    private Loader load = new Loader();
    private Inbox inbox = new Inbox();
    private int REG = 4;
    private Account account = new Account();
    private AccountDAO adao = null;
    private Outbox outbox = new Outbox();
    private OutboxDAO outboxDAO = null;

    //Fungsi yang digunakan untuk parsing data dari XML ke message
    public synchronized message getMessageData(String xml) {
        message msg = new message();
        Document doc = null;
        int type = 0;
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();
            InputSource inStream = new InputSource();
            inStream.setCharacterStream(new StringReader(xml));
            doc = (Document) db.parse(inStream);
        } catch (SAXException ex) {
            Logger.getLogger(XMLFactory.class.getName()).log(Level.SEVERE, null, ex);
            return msg;
        } catch (IOException ex) {
            Logger.getLogger(XMLFactory.class.getName()).log(Level.SEVERE, null, ex);
            return msg;
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(XMLFactory.class.getName()).log(Level.SEVERE, null, ex);
            return msg;
        }

        //Digunakan untuk mendapatkan Pengirim dan Penerima
        Element MyNumber = (Element) doc.getElementsByTagName("message").item(0);
        Element Client = (Element) doc.getElementsByTagName("message").item(0);

        //MEMBALIK PENERIMA DAN PENGIRIM
        msg.setReceiver(Client.getAttribute("to").trim());
        msg.setSender(MyNumber.getAttribute("from").trim());
        Element root = doc.getDocumentElement();
        NodeList children = root.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (child instanceof Element) {
                Element childElement = (Element) child;
                Text textNode = (Text) childElement.getFirstChild();
                if (textNode != null) {
                    String text = textNode.getData().trim();
                    if (childElement.getTagName().equals("body")) {
                        msg.setBody(text);
                        System.out.println("======DATA YANG DIKIRIMKAN=====");
                        System.out.println("PENGIRIM    : " + msg.getSender());
                        System.out.println("PENERIMA    : " + msg.getReceiver());
                        System.out.println("BODY        : " + msg.getBody());
                        //Proses Message
                        this.filterPing(msg);
                    }
                }
            }
        }
        return msg;
    }

    //fungsi yang digunakan untuk memeriksa XML
    public void filterMessage(String text) {
        System.out.println("<===CEK XML TYPE FROM GATEWAY===>");
        getMessageData(text);
    }

    //fungsi yang digunakan untuk memeriksa body message untuk layanan PING
    public synchronized void filterPing(message message) {
        Integer PING = 4;
        Integer length = message.getBody().length();
        if (message.getBody() != null) {
            if (length == PING) {
                if (message.getBody().equalsIgnoreCase("PING")) {
                    System.out.println("========MESSAGE PING TYPE==========");
                    try {
                        Outbox otbx = new Outbox();
                        otbx.setReceiver(message.getSender());
                        otbx.setText("Reply from gateway.......");
                        OutboxDAO otbxDAO = new OutboxDAO(DBConnection.getInstance().getCon());
                        otbxDAO.insert(otbx);
                        System.out.println("   ==Success save to outbox==");
                    } catch (SQLException ex) {
                        System.out.println("Service ping failed in connection database....");
                        Logger.getLogger(XMLFactory.class.getName()).log(Level.SEVERE, null, ex);
                    }

                } else {
                    System.out.println("===MESSAGE REQUEST SERVICE TYPE==");
                    try {
                        inbox.setSender(message.getSender());
                        inbox.setText(message.getBody());
                        InboxDAO inboxDAO = new InboxDAO(DBConnection.getInstance().getCon());
                        inboxDAO.insert(inbox);
                        System.out.println("==Success save to inbox==");
                    } catch (SQLException ex) {
                        System.out.println("Service insert inbox failed in connection database....");
                        Logger.getLogger(XMLFactory.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
//                else if (length >= PING) {
//                List<String> list = Parser.getTokenList(message.getBody(), "#");
//                int key = list.size();
//                if (key == REG) {
//                    try {
//                        System.out.println("==MESSAGE REGISTRATION TYPE==");
//                        if (list.get(1) != null && list.get(2) != null && list.get(3) != null) {
//                            if (list.get(0).equalsIgnoreCase("REG")) {
//                                adao = new AccountDAO(DBConnectionuser.getInstance().getCon());
//                                account.setID(list.get(1));
//                                account.setUsername(list.get(2));
//                                account.setPassword(list.get(3));
//                                account.setNotelp(message.getSender());
//                                System.out.println("ID          : " + account.getID());
//                                System.out.println("User        : " + account.getUsername());
//                                System.out.println("Password    : " + account.getPassword());
//                                System.out.println("No. Telepon : " + account.getNotelp());
//                                if (adao.load(account)) {
//                                    adao.insert(account);
//                                    outbox.setReceiver(account.getNotelp());
//                                    outbox.setText("Registrasi user sukses...");
//                                    outboxDAO = new OutboxDAO(DBConnection.getInstance().getCon());
//                                    outboxDAO.insert(outbox);
//                                } else {
//                                    System.out.println("User sudah digunakan");
//                                    outboxDAO = new OutboxDAO(DBConnection.getInstance().getCon());
//                                    outbox.setReceiver(account.getNotelp());
//                                    outbox.setText("User sudah digunakan silahkan registrasi kembali...");
//                                    outboxDAO.insert(outbox);
//                                }
//                            } else {
//                                inbox.setSender(message.getSender());
//                                inbox.setText(message.getBody());
//                                InboxDAO inboxDAO = new InboxDAO(DBConnection.getInstance().getCon());
//                                inboxDAO.insert(inbox);
//                                System.out.println("  ===Success save to inbox===");
//                            }
//
//                        } else {
//                            outboxDAO = new OutboxDAO(DBConnection.getInstance().getCon());
//                            outbox.setReceiver(account.getNotelp());
//                            outbox.setText("Format pesan salah...");
//                            outboxDAO.insert(outbox);
//                        }
//                    } catch (SQLException ex) {
//                        Logger.getLogger(XMLFactory.class.getName()).log(Level.SEVERE, null, ex);
//                    }
//
//
//                } else {
//                    try {
//                        System.out.println("====MESSAGE REQUEST SERVICE TYPE===");
//                        inbox.setSender(message.getSender());
//                        inbox.setText(message.getBody());
//                        InboxDAO inboxDAO = new InboxDAO(DBConnection.getInstance().getCon());
//                        inboxDAO.insert(inbox);
//                        System.out.println("  ===Success save to inbox===");
//                    } catch (SQLException ex) {
//                        Logger.getLogger(XMLFactory.class.getName()).log(Level.SEVERE, null, ex);
//                    }
//
//                }
//
//            }
        else {
                System.out.println("====MESSAGE REQUEST SERVICE TYPE===");
                try {
                    inbox.setSender(message.getSender());
                    inbox.setText(message.getBody());
                    InboxDAO inboxDAO = new InboxDAO(DBConnection.getInstance().getCon());
                    inboxDAO.insert(inbox);
                    System.out.println("  ===Success save to inbox===");
                } catch (SQLException ex) {
                    System.out.println("Service insert inbox failed in connection database....");
                    Logger.getLogger(XMLFactory.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        } else {
            System.out.println("Text:  EMPTY");
        }
    }
}
